<?php
// Check driver destinations near my destinations.
// For those drivers, add the origin as passenger, and destinations as the start and end point of the driver.
// Post-process the results and work out minimum totals for driver start and end.
require_once ("include.php");
require_once ("registereduserobj.php");
require_once ("journeyobj.php");
if ($userid = authenticate(false)) {
 $userjourney = new journey();
 if (isset($_REQUEST['newjourney']) && $_REQUEST['newjourney'] == 'Y') {
  $userjourney->remove($userid);
  unset($_SESSION['journey']);
 }
 if ($userjourney->readjourney($userid)) {
  // We already have a lift programmed in.
  // The journey file only ever has a list of current trips.
  echo showlifts($userid);
 } else {
  if ($userjourney->applyfromrequest()) {
   // Set up a journey from a rest enquiry
   echo showlifts($userid,$userjourney);
  } else {
   // Get journey details
   echo showauthuser($userid);
  }
 }
} else {
 // The splash page
 echo notloggedon();
}

function showlifts($userid,$userjourney) {

($userjourney->header[13] =='D') ? $lookfor = 'P' : $lookfor = 'D' ; 

$lat = $userjourney->header[7];$lng = $userjourney->header[8];
$sql = "select * from journey where journeytypeid = '$lookfor' order by haversine(destlat,destlng,$lat,$lng) desc limit 1";
$ans = sqlreadarray($sql);

//We can only pass addresses in otherwise we can't make sense of the results.
$others = array(); $idlist = array();
foreach ($ans as $id=>$item) {
 $others[] = $item[9];
 $others[] = $item[1];
 $idlist[] = $item[0];
 $idlist[] = $item[0];
}
$others = json_encode($others);
$idlist = json_encode($idlist);
$us = json_encode(array($userjourney->header[1]));
$userdest = $userjourney->header[1];
$userprefs = freaditem('userpref',$userid);
$rand=microtime();

$o = <<< STARTTAG
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
 function newjourney() {
  document.form.newjourney.value='Y';
  document.form.submit();
 }
</script>
</head>
<body>
<div data-role="page">
 <div data-role="header">
   <a href="logout.php data-role="button" >Exit</a>
   <h1>Official Liftmate Site</h1>

 </div>
 <form name=form>
  <input type=hidden name=newjourney value=''>
 </form>
<h2>Showing Lift</h2>
Looking for lifts to : $userdest
<button type=button onclick='newjourney()' data-inline="true">Go somewhere else</button>
<pre>
<div id=ans>
</div>
<div id=ans2>
</div>
</pre>
  <div data-role="footer">
    <h1>Footer Text</h1>
  </div>
</div> 
</body>

<script>
 var service = new google.maps.DistanceMatrixService();
 var obj = new Object() ;
 obj.origins = $others ; // This is in pairs
 obj.destinations = $us ;
 var idlist = $idlist;
 obj.travelMode = google.maps.TravelMode.DRIVING ;
 console.log($others);
 console.log($us);
 service.getDistanceMatrix(obj,callback);

function callback(response, status) {
 if (status == google.maps.DistanceMatrixStatus.OK) {

  var outtable = '<table>';
  for (var c=0;c< response.originAddresses.length;c = c + 2) {
   
   outtable = outtable + '<tr>';
   outtable = outtable + '<th>' + response.originAddresses[c] + '</th>';
   outtable = outtable + '<th>' + response.originAddresses[c+1] + '</th>';

   outtable = outtable + '<td>';
   outtable = outtable + (response.rows[c].elements[0].duration.value+response.rows[c+1].elements[0].duration.value);
   outtable = outtable + '</td>';

   outtable = outtable + '<td>';
   outtable = outtable + idlist[c];
   outtable = outtable + '</td>';

   outtable = outtable + '</tr>';
  }
  outtable = outtable + '</table>';
  document.getElementById('ans').innerHTML = outtable;
  
 } else {
  console.log(status);
 }
}

</script>
</html>
STARTTAG;
 return $o;
}

function showauthuser($userid) {

 // Default driver or passenger ? Note there needs not be any preferences.
 $userprefs = freaditem('userpref',$userid);
 $driverpassenger = @$userprefs[5];
 if($driverpassenger != 'D') {
  $driverpassenger = 'D';
 }

 if($driverpassenger == 'P') {
  $o = passengerpage();
 } else {
  $o = driverpage($userid,$userprefs);
 }

 return $o;
}

function passengerpage() {
 $o = '';
 return $o;
}

function driverpage($userid,$userprefs) {

 $sql = "select name,formatted_address,lat,lng from location where current = 'Y' and userid = '$userid'";
 $locations = sqlreadassoc($sql);
 $dests = '<h1>Saved Destinations</h1>';
 $departs = '<h1>Saved Departures</h1>';
 foreach($locations as $itemid => $item) {
  $name = $item['name'];
  $jsonitem = json_encode($item);
  $dests .= "<p><button data-theme=b type='button' onclick='setdestaddress($jsonitem);'>$name</button></p>";
  $departs .= "<p><button type='button' onclick='setdepartaddress($jsonitem);'>$name</button></p>";
 }
 $dests .= "<p><button type=button onclick='goback()'>Search</button></p>";
 $departs .= "<p><button type=button onclick='goback()'>Search</button></p>";
 $departs .= "<p><button type=button onclick='current()'>Current Location</button></p>";
 $rand = microtime();

 $o = <<< STARTTAG
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<meta name="viewport" content="initial-scale=1, maximum-scale=5">

<script>
var placeSearch, autocompletedepart, autocompletedest;
function initialize() {
 autocompletedest = new google.maps.places.Autocomplete(
   document.getElementById('destname'),
   {types: ['geocode'], componentRestrictions: {country: 'nz'}}
 );
 google.maps.event.addListener(autocompletedest, 'place_changed', function() {setdestaddressg(autocompletedest.getPlace());});	 

 autocompletedepart = new google.maps.places.Autocomplete(
   document.getElementById('departname'),
   {types: ['geocode'], componentRestrictions: {country: 'nz'}}
 );
 google.maps.event.addListener(autocompletedepart, 'place_changed', function() {setdepartaddressg(autocompletedepart.getPlace());});

}

function goback() {
 $.mobile.changePage('#pageone' );
}
function current() {
 $.mobile.changePage('#pageone' );
}
function setdestaddress(place) {
  // From DB
 document.getElementById('destaddress').value = place.formatted_address;
 document.getElementById('destlat').value = place.lat;
 document.getElementById('destlng').value = place.lng;
 document.getElementById('destname').value = place.formatted_address;
 $.mobile.changePage('#pageone' );
}

function setdepartaddress(place) {
  // From DB
 $("#departaddress").value = place.formatted_address;
 $("#departlat").value = place.lat;
 $("#departlng").value = place.lng;
 $("#departname").value = place.formatted_address; 
 $.mobile.changePage('#pageone' );
}

	 
function setdestaddressg(place) {
  // From Google places
 $("#desttaddress").value = place.formatted_address;
 $("#destlat").value = place.geometry.location.lat();
 $("#destlng").value = place.geometry.location.lng();
 $("#destname").value = place.formatted_address; 
 $("#destreference").value = place.reference;
 
}

function setdepartaddressg(place) {
  // From Google places
 $("#departaddress").value = place.formatted_address;
 $("#departlat").value = place.geometry.location.lat();
 $("#departlng").value = place.geometry.location.lng();
 $("#departname").value = place.formatted_address; 
 $("#departreference").value = place.reference;
}

function geolocate() {
  var currentloc ;
  if (navigator.geolocation) {
	  navigator.geolocation.getCurrentPosition(geosuccess);
  }	
}

function geosuccess(position) {
  var geolocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  autocompletedepart.setBounds(new google.maps.LatLngBounds(geolocation, geolocation));
  geocoder = new google.maps.Geocoder();
  geocoder.geocode(
    {'latLng': geolocation}, 
    function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        document.getElementById("departname").value = results[0].formatted_address ;
        setdepartaddressg(results[0]);
      }
    }
  );
}

function reviewsubmit() {
 // Address must be different
 // Both must be filled in.
 
 enablesubmit();
}

function disablesubmit() {
 $("#subbut").button('disable'); 	
}

function enablesubmit() {
 $("#subbut").button('enable');
}

function dosub() {
 var now = new Date();
 now.setMinutes(now.getMinutes() + 30);
 document.form.departtime.value = now.getFullYear()+"-"+(now.getMonth()+1)+"-"+now.getDate()+" "+now.getHours()+":"+now.getMinutes()+":"+now.getSeconds();
 document.form.submit();
}

function setdepartaddress(place) {
  // From DB
 document.form.departaddress.value = place.formatted_address;
 document.form.departlat.value = place.lat;
 document.form.departlng.value = place.lng;
 document.form.departname.value = place.formatted_address; 
 $.mobile.changePage('#pageone' );
}


$(document).on('pageinit',"#pageone", function() {
initialize();
geolocate();
document.getElementById('destname').focus();
 
});



</script>
<style>
.ui-body-c
{
background:black;
color:white;

}
</style>
</head>

<body>
<div data-theme=c data-role="page" id="pageone">
 <div data-role="header">
 <h1><a href=logout.php rel="external">Logout</a></h1>
 </div>

 <div>Looking for a passenger</div>
 <form name=form>
 <input type=hidden id=destlat name=destlat value=''>
 <input type=hidden id=destlng name=destlng value=''>
 <input type=hidden id=destaddress name=destaddress value=''>
 <input type=hidden id=destreference name=destreference value=''>
 <input type=hidden id=departlat name=departlat value=''>
 <input type=hidden id=departlng name=departlng value=''>
 <input type=hidden id=departaddress name=departaddress value=''>
 <input type=hidden id=departreference name=departreference value=''>
 <input type=hidden id=departtime name=departtime value=''>


 <div data-role="fieldcontain">
  <label for="destname"><a href='#pagetwo' data-transition="slidefade">Destination</a></label>
  <input onfocus='disablesubmit()' onblur = 'reviewsubmit();' id="destname" placeholder=" address" type=text></input>
 </div>
 <div data-role="fieldcontain">
  <label for="departname"><a href='#pagethree' data-transition="slidefade">Depart From</a></label>
  <input onfocus='disablesubmit()' onblur = 'reviewsubmit()' id="departname" placeholder="Starting address" type="text"></input> 
 </div>
 <div data-role="fieldcontain">
  <label for="subbut">When Leaving</label>
  <input type="range" name="points" id="points" value="50" min="0" max="100">
 </div>
 <button id=subbut disabled=disabled type=button onclick='dosub()'>Find a lift</button>
 </form>

 <div data-role="footer">
  <h1>Footer Text</h1>
 </div>
</div>

<div data-role="page" id="pagetwo">
  <div data-role="header">
    <h1>Welcome To My Homepage</h1>
  </div>
$dests
  <div data-role="footer">
    <h1>Footer Text</h1>
  </div>
</div>


<div data-role="page" id="pagethree">
  <div data-role="header">
    <h1>Welcome To My Homepage</h1>
  </div>
$departs
  <div data-role="footer">
    <h1>Footer Text</h1>
  </div>
</div> 


</body>
</html>
STARTTAG;

 return $o;

}

?>

